﻿using Common.Lib.Service;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Lib.Service
{
    public class HttpRestClient
    {
        public readonly string apiUrl;

        protected readonly RestClient client;

        /// <summary>
        /// HttpRestSharp客户端
        /// </summary>
        public HttpRestClient(string apiUrl)
        {
            this.apiUrl = apiUrl;
            client = new RestClient(apiUrl);
        }

        public async Task<ApiResponse<T>?> ExecuteAsync<T>(BaseRequest baseRequest)
        {
            var request = new RestRequest(apiUrl + baseRequest.Route, baseRequest.Method);            
            request.AddHeader("Accept", "application/json");
            request.AddHeader("Content-Type", "application/json"); 
            if(baseRequest.Parameter != null)
            {
                request.AddParameter("", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
                //request.AddJsonBody(baseRequest.Parameter);
            }
            //client.BuildUri(request);
            var response = await client.ExecuteAsync(request);
            return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content);
        }
    }
}
